import axios from 'axios'
import { Loading, Message } from 'element-ui'
import {baseUrl} from '@/config';

let loading = null
function loadingstart () {
  loading = Loading.service({
    lock: true,
    text: '数据加载中',
    background: 'rgba(255,255,255,.6)'
  })
}
function loadingend () {
  loading.close()
}

const service = axios.create({
  baseURL: baseUrl,
  // 跨域携带token
  withCredentials: true,
  timeout: 50000,
  validateStatus (status) {
    // 一般来说，http status为200-300之间时，均判定为请求通过，你可以在这里修改这个配置(不建议修改)
    return status === 200
  },
  headers: {
    // 定义 post 请求编码格式
    post: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  }
})
// 发送前拦截
service.interceptors.request.use(
  config => {
    loadingstart()
    // console.log(config)
    // 这里和后端商量添加
    // let token = window.localStorage.getItem('token');
    // token ? config.headers['Authorization'] = token : config.headers['Authorization'] = ""
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// 响应拦截
service.interceptors.response.use(
  resspose => {
    loadingend()
    // eslint-disable-next-line eqeqeq
    if (resspose.data.status == 200) {
      return Promise.reject(resspose)
    }
    return resspose
  },
  (error) => {
    loadingend()
    console.log(error)
    if (!error.response) {
      // eslint-disable-next-line prefer-promise-reject-errors
      return Promise.reject({
        msg: '网络连接超时',
        error
      })
    }
    let msg = ''
    const status = error.response.status
    switch (status) {
      case 400:
        msg = '输入不合法'
        break
      case 401:
        msg = '没有该操作权限'
        break
      case 403:
        msg = '请登录'
        break
      case 404:
        msg = '服务器走丢了'
        break
      case 500:
      case 501:
      case 502:
      case 503:
      case 504:
        msg = '服务器错误'
        break
      default:
        msg = '网络繁忙' + status
    }
    Message({
      type: 'error',
      message: msg
    })
    // eslint-disable-next-line prefer-promise-reject-errors
    return Promise.reject({
      error
    })
  }
)
export default service
